import tensorflow as tf
import matplotlib.pyplot as plt

# 加载数据集
(train_image, train_label), (test_image, test_label) = tf.keras.datasets.fashion_mnist.load_data()

# 查看train_image shape
print(train_image.shape)
print(train_label)

# 输出：(9, 0)，可见标签是从0到9，10个类别
print(train_label.max())
print(train_label.min())

# 打印一张图片
plt.imshow(train_image[0])
plt.show()

train_image = train_image / 255
test_image = test_image / 255

model = tf.keras.Sequential()

# 添加Flatten层将（28,28）的数据变成[28*28]
model.add(tf.keras.layers.Flatten(input_shape=(28, 28)))
model.add(tf.keras.layers.Dense(64, activation='relu'))
model.add(tf.keras.layers.Dense(10, activation='softmax'))

model.summary()

# sparse_categorical_crossentropy种类超过2两种，像这里面0到9游十种
model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['acc'])

history = model.fit(train_image, train_label, epochs=20)

plt.plot(history.epoch, history.history.get('acc'))
plt.xlabel('epochs')
plt.ylabel('acc')
plt.show()

# 用测试集对训练好的模型进行测试
print(model.evaluate(test_image, test_label))

